package com.totoro.rpc.register;

import com.totoro.rpc.common.util.NetworkUtil;
import lombok.extern.slf4j.Slf4j;
import org.I0Itec.zkclient.ZkClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.UnknownHostException;
import java.util.HashSet;
import java.util.Set;

/**
 * 基于Zookeeper的服务注册实现
 * Created by Niki on 2018/5/7 17:48
 */
@Slf4j
public class ZookeeperRegister implements Register {
    private final ZkClient zkClient;

    private ZookeeperConfig zookeeperConfig;

    public ZookeeperRegister(String zkAddress, int session_timeout, int connection_timeout) {
        this.zkClient = new ZkClient(zkAddress, session_timeout, connection_timeout);
        log.debug("register connect zookeeper");
    }


    public void registerService(String serverName,String version, String serviceAddress) {
        String serverPath = ZookeeperUtil.serverPath(serverName, version);
        register(serverPath, serviceAddress);
    }

    public void registerClient(String serverName, String serviceAddress) {
        String clientPath = ZookeeperUtil.clientPath(serverName);
        register(clientPath, serviceAddress);
    }

    private void register(String serverPath, String serviceAddress) {
        if (!zkClient.exists(serverPath)) {
            zkClient.createPersistent(serverPath, true);
        }
        Set<String> addresses = zkClient.readData(serverPath);
        if (addresses == null) {
            addresses = new HashSet<String>();
        }

        boolean addressHeath = NetworkUtil.serverHeath(serviceAddress);
        if (!addressHeath) {
            log.error("地址：{}，监测不可达，无法完成注册！", serviceAddress);
        }
        addresses.add(serviceAddress);
    }


//    public static void main(String[] args) {
//        ZkClient client = new ZkClient("172.20.10.222:2181", 5000, 1000);
//        String path = serverPath("com.totoro.demo.Server");
//        if (client.exists(path)) {
//            Set<String> addresses = client.readData(path);
//            System.out.println(addresses);
//            addresses.add("127.0.0.1:10299");
//            client.writeData(path, addresses);
//        }
//    }
}
